<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 前台订单ajax
 * @package  ajax
 * @subpackage  shop
 * @author   allen.qiang
 */

class ajax_bill {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //提交订单
                    $this->submitShopBill();
                    break;

                case 3: //取消订单
                    $this->cancelBill();
                    break;

                case 4: //获得订单列表信息
                    $this->getBillList();
                    break;

                case 6: //获得订单商品
                    $this->getBillGoods();
                    break;

                case 7: //检查在线支付订单状态
                    $this->checkOnlinePay();
                    break;
		        //mod by 20141106 allen.qiang FUN-AC-0013-销售BD双11活动 start
                case 8:
                    //$this->activities();
                    break;
                //mod by 20141106 allen.qiang FUN-AC-0013-销售BD双11活动 end
 				//add by 201411018 allen.qiang FUN-AC-0018-感恩节活动 start
                case 9:
                    //$this->use_Integral();
                    break;
				//add by 201411018 allen.qiang FUN-AC-0018-感恩节活动 end
                default:
                    $this->toReturn('参数错误');
                    break;
            }

        } else {

            $this->toReturn('参数错误');

        }

    }

    /**
     * 返回信息
     * @param string $message
     * @param int $code
     * @param mixed $data
     */
    private function toReturn( $message, $code = 400, $data = '' ) {

        die( json_encode( array( 'code' => $code, 'message' => $message, 'data' => $data ) ) );

    }


    /**
     * 取消订单
     */
    private function cancelBill() {

        global $G_SHOP;

        if (!$G_SHOP->currentPCustID) {
            returnJsonData('请先登录', 404);
        }

        if (!isset($_REQUEST['bill_no']) || empty($_REQUEST['bill_no'])) {
            returnJsonData('参数错误');
        }

        quanli_include('module/base/bill/billEdit.class.php');

        //实例订单类
        $billEdit = new billEdit( $G_SHOP->DBCA );

        //取消订单
        $result_array = $billEdit->cancelBill( $_REQUEST['bill_no'], $G_SHOP->currentCustomerID );

        returnJsonData($result_array['message'], $result_array['code']);

    }


    /**
     * 提交普通订单
     */
    private function submitShopBill() {

        global $G_SHOP;

        //检查是否登录
        if (!$G_SHOP->currentPCustID) {
            returnJsonData('请先登录');
        }

        //默认购物车名称数组。（注：除了shop_cart和now_buy为系统购物车名称外，其他的有在线的也有下线的暂时不处理，先保留吧！）
        $cartNameArr = array('shop_cart', 'now_buy','now_buy_miaosha','now_buy_shengbang','now_buy_LV5','now_buy_ny_xyk','now_buy_bd11','now_buy_cbc','now_buy_Gingerbread','now_buy_pf','now_buy_christmas','now_buy_activity','now_buy_valentine_BD','now_buy_womensday');

        //读取activity_config活动配置表，获取所有活动编码:config_code和渠道ID:config_value add by allen.qiang Start
        $activityConfigSql = "SELECT config_code,config_value FROM `activity_config` WHERE config_key = 'billPromotion'";
        $activityConfigRows = $G_SHOP->DBCA->stmt_query($activityConfigSql);

        //不空重新组织购物车数组
        if(!is_null($activityConfigRows) && count($activityConfigRows) > 0){
            foreach($activityConfigRows as $config){
                $tempCartNameArr[] = $config->config_code;
            }
            //合并购物车数组
            $cartNameArr = array_merge($cartNameArr,$tempCartNameArr);
        }

        //读取activity_config活动配置表，获取所有活动编码:config_code和渠道ID:config_value add by allen.qiang End

        //非系统购物车或活动以外的不可提交订单
        if (!in_array($_REQUEST['act'], $cartNameArr)) {
            returnJsonData('参数错误');
        }

        //加载相关类
        quanli_include('module/base/shop/shopCart.class.php');
        quanli_include('module/base/system/itemHandler.class.php');
        quanli_include('module/base/common/quanliHttp.class.php');
        quanli_include('module/base/bill/billEdit.class.php');
        quanli_include('module/base/goods/goodsDeliver.class.php');
        quanli_require('module/base/goods/quanliGoods.class.php');
        quanli_require('module/base/activity/activityConfig.class.php');                        //加载活动配置类

        //实例http类
        $quanliHttp = new quanliHttp();

        //实例化购物车类
        $shopCart = new shopCart();

        //实例化商品配送时间类
        $goodsDeliver = new goodsDeliver();

        //实例化商品类
        $quanliGoods = new quanliGoods($G_SHOP->DBCA);

        //获取购物车明细
        $bill_array = $shopCart->getCartInfo($_REQUEST['act']);


        //以下代码块是定制活动类代码，暂注释------------start

        //<<<<<<<<<<需优化（制订一套统一的标准，计划加一个全局控制器）add by allen.qiang Start
        //这部分代码是各定制活动需要的代码，暂时注释掉。需要时再放开，或优化逻辑。
        //del by allen.qiang 20170206 删除冗余代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//        //add allen.qiang 20141030 农业银行信用卡五折购 start
//        quanli_require('module/base/activity/activitySpike.class.php');
//        $activityspike=new activitySpike();
//        if(isset($bill_array['master']['billPromotion']) &&
//            ($bill_array['master']['billPromotion'] == $activityspike->billPromotion_ny_xyk)){
//            //是否含有一磅蛋糕
//            $isbool=false;
//            $general=$bill_array['goods']['general'];
//            foreach($general as &$goods){
//                if($goods['spec']=="1磅" && $goods['goodsName']!="悦时光")
//                    $isbool=true;
//            }
//            //使用优惠券
//            $use_coupon = 0;
//            if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
//                $use_coupon = 1;
//            }
//            if(($bill_array['master']['payTypeID']==$activityspike->payTypeID_ny_xyk || $bill_array['master']['payment_method_id']==$activityspike->paymentID_ny_xyk) && $bill_array['master']['cityid']==110 && $activityspike->nh_xyk_isDate() && $isbool && $activityspike->nh_xyk_num()>0){ //判断是否是用农业银行信用卡支付且在活动时间内并且是上海站的1磅蛋糕
//                if($bill_array['use_points']['bill_points_money']>0 || $use_coupon==1 || (isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail']))){ //农业银行信用卡五折购不能享受现金卡、专享卡、优惠券、红包、积分、会员等级制度
//                    $bill_array['master']['billPromotion']=0;
//                }
//            }else{
//                $bill_array['master']['billPromotion']=0;
//            }
//        }
//        //add allen.qiang 20141030 农业银行信用卡五折购 end
//        //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---start
//        quanli_require('module/base/activity/activityCbc.class.php');
//        //实例建设银行五折购活动类
//        $activityCBC=new activityCbc();
//        $activity_master=$activityCBC->activity_master($_REQUEST);
//        if(isset($bill_array['master']['billPromotion']) &&
//            ($bill_array['master']['billPromotion'] == $activity_master["billPromotion"]) ){
//            //是否含有一磅蛋糕
//            $isbool=false;
//            $general=$bill_array['goods']['general'];
//            foreach($general as &$goods){
//                if($goods['spec']=="1磅" && $goods['goodsName']!="悦时光")
//                    $isbool=true;
//            }
//            //使用优惠券
//            $use_coupon = 0;
//            if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
//                $use_coupon = 1;
//            }
//            if($bill_array['master']['payment_method_id']==$activity_master["paymentID_CBC"] && $bill_array['master']['cityid']==110 && $activity_master["isDate"]==1 && $isbool && $activity_master["activity_num"]>0){ //判断是否是用建行信用卡支付且在活动时间内并且是上海站的1磅蛋糕
//                if($activity_master["activity_status"]==1){
//                    returnJsonData('抱歉，您今日已购买过建设银行信用卡五折购蛋糕！');
//                }
//                if($bill_array['use_points']['bill_points_money']>0 || $use_coupon==1 || (isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail']))){ //建行信用卡五折购不能享受现金卡、专享卡、优惠券、红包、积分
//                    $bill_array['master']['billPromotion']=0;
//                }
//            }else{
//                $bill_array['master']['billPromotion']=0;
//            }
//
//        }
//        //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---end
//        //add by 20141219 sun.qiang 三八 ---start
//        quanli_require('module/base/activity/activityWomensday.class.php');
//        $activityWomensday=new activityWomensday();
//        $_REQUEST["pcustID"]=$G_SHOP->currentPCustID;
//        $activity_womensday=$activityWomensday->activity_master($_REQUEST);
//
//        if(isset($bill_array['master']['billPromotion']) &&
//            ($bill_array['master']['billPromotion'] == $activity_womensday['billPromotion'])){
//
//            if($activityWomensday->buy_count($G_SHOP->currentPCustID,$activity_womensday['billPromotion']) > 0)
//            {
//                returnJsonData('您今日已购买过活动蛋糕，欢迎明日再来订购');
//            }
//            if($activity_womensday['activity_num']<=0)
//            {
//                returnJsonData('活动蛋糕已售罄');
//            }
//        }
//        //add by 20141219 sun.qiang 三八 ---end
        //需优化（制订一套统一的标准，计划加一个全局控制器）add by allen.qiang End>>>>>>>>>>
        //del by allen.qiang 20170206 删除冗余代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        //以下代码块是定制活动类代码，暂注释-------------end


        if ($bill_array['master']['is_match'] == 0) {
            returnJsonData('超出配送范围，请重新选择地址，或选择自提点自提');
        }

        //应收金额为0的情况，采用现金支付方式
        if($_REQUEST['is_zero'] == 1){
            //默认采用现金支付
            $bill_array['master']['payTypeID'] = 1;
            $bill_array['master']['pay_type'] = 1;
            $bill_array['master']['payTypeName'] = '货到付款';
            $bill_array['master']['payment_method_id'] = 58;
            $bill_array['master']['payment_method_name'] = '现金支付';
            $bill_array['master']['payment_method_type'] = 1;
            $_REQUEST['pay_type_radio'] = 2;
        }

        //检查支付方式类型
        if( !isset($_REQUEST['pay_type_radio']) || !in_array($_REQUEST['pay_type_radio'], array(1, 2)) ){
            returnJsonData('请选择支付方式类型');
        }

        //检查收货地址
        if (!isset($bill_array['master']['deliverid']) || empty($bill_array['master']['deliverid'])) {
            returnJsonData('请选择收获地址');
        }


        //站点自提 add by allen.qiang 2015-06-29
        if($bill_array['master']['deliver_type'] == 2){

            //配送站ID
            $distribution_id = $bill_array['master']['distribution_id'];

            //配送站地址
            $distributionInfo = $G_SHOP->DBCA->stmt_query('SELECT provinceName,cityName,countyName,provinceid,cityid,countyid,address FROM sys_distribution WHERE distribution_id = '.$distribution_id);

            //更新配送地址
            $bill_array['master']['deliver_province'] = $distributionInfo[0]->provinceName;
            $bill_array['master']['deliver_city'] = $distributionInfo[0]->cityName;
            $bill_array['master']['deliver_county'] = $distributionInfo[0]->countyName;
            $bill_array['master']['deliver_address'] = $distributionInfo[0]->address;
            $bill_array['master']['provinceid'] = $distributionInfo[0]->provinceid;
            $bill_array['master']['cityid'] = $distributionInfo[0]->cityid;
            $bill_array['master']['countyid'] = $distributionInfo[0]->countyid;

        }

        //检查配送方式
        if (!isset($bill_array['master']['sendTypeID']) || empty($bill_array['master']['sendTypeID'])) {
            returnJsonData('请选择配送方式');
        }

        //检查支付方式
        if (!isset($bill_array['master']['payTypeID']) || empty($bill_array['master']['payTypeID'])) {
            returnJsonData('请选择支付方式');
        }

        //检查配送时间
        if (!isset($bill_array['master']['send_date']) || empty($bill_array['master']['send_date'])) {
            returnJsonData('请选择配送日期');
        }

        //检查配送开始时间
        if (!isset($bill_array['master']['send_start_time']) || empty($bill_array['master']['send_start_time'])) {
            returnJsonData('请选择配送开始时间');
        }


        //读取活动配置信息 add by allen.qiang Start

        //实例化全局配置
        $systemConfig = new activityConfig('systemConfig');
        $sysConfig = $systemConfig->config;

        //实例化活动配置
        $activityConfig = new activityConfig($_REQUEST['act']);
        $config = $activityConfig->config;

        //活动是否有效
        $haveActivity = false;

        //如果活动在线
        if($config && date(G_DEFAULT_DATETIME_FORMAT)>$config['start_time'] && date(G_DEFAULT_DATETIME_FORMAT)<$config['end_time']){

            $haveActivity = true;

            //判断今天是否在已排除的周期活动内
            if(isset($config['exclude_week']) && !empty($config['exclude_week'])){
                $w = date('w');
                if(is_array(json_decode($config['exclude_week'])) && in_array($w,json_decode($config['exclude_week']))){
                    $haveActivity = false;
                }
            }

            //检查支付方式
            $payTypeID = !empty($config['payTypeID'])?explode(',',$config['payTypeID']):array();
            $paymentID = !empty($config['paymentID'])?explode(',',$config['paymentID']):array();

            $paymentIDs = array_merge($payTypeID,$paymentID);

            if(!empty($paymentIDs) && !in_array($bill_array['master']['payTypeID'],$paymentIDs)){
                returnJsonData('对不起，本活动不支持'.$bill_array['master']['payTypeName']);
            }

            //配送间隔
            $send_date_interval = isset($config['send_date_interval'])&&$config['send_date_interval']>0?intval($config['send_date_interval']):0;

            //判断订单提交时间节点
            if($haveActivity && isset($config['submit_bill_time_node']) && date('H:i:s') > $config['submit_bill_time_node']){

                //自定义配送时间数组
                $custom_send_time_array = (array)json_decode($config['custom_send_time']);

                //星期数组
                $week_array = array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");

                //配送间隔加1
                ++$send_date_interval;

                $userSendDate = $bill_array['master']['send_date'];
                $custSendDate = date(G_DEFAULT_DATE_FORMAT, strtotime("+$send_date_interval day"));

                //用户配送时间大于自定义配送时间提示后刷新页面
                if($userSendDate<$custSendDate){

                    $date_array = array(
                        'date_show' => date('m月d日', strtotime("+$send_date_interval day")),
                        'week' => $week_array[date('w', strtotime("+$send_date_interval day"))]
                    );

                    $txt = $date_array['date_show'].$date_array['week'].'&nbsp;'.$custom_send_time_array['send_start_time'].'~'.$custom_send_time_array['send_end_time'];

                    $msg = isset($config['time_node_tips'])&&!empty($config['time_node_tips'])?$config['time_node_tips']:'亲您的订单信息已修改配送时间为</br>%s';

                    $message = str_replace('%s', $txt, $msg);

                    returnJsonData($message,201);

                }else{
                    //这里是为了防止用户客户端JS加载失败导致配送时间写入失败，变成默认的配送时间 add by allen.qiang 2015-05-07
                    $bill_array['master']['send_start_time'] = $custom_send_time_array['send_start_time'];
                    $bill_array['master']['send_end_time'] = $custom_send_time_array['send_end_time'];
                }
            }

            if($_REQUEST['source'] == 'wap' && $haveActivity){
                $bill_array['master']['billPromotion'] = $config['billPromotion'];
            }
        }

        /*
         * ===============================
         * ===========商品信息Start============
         * ===============================
         */

        $bill_goods = array();

        $max_interval = 0;                                                              //配送间隔
        $start_time = '';                                                               //起始配送时间
        $end_time = '';                                                                 //结束配送时间
        $cutTime =  '';                                                                 //截单时间
        $startDeliver = '';
        $endDeliver = '';
        $startDeliverTime = '';                                                         //当天最迟配送商品最早配送开始时间
        $endDeliverTime = '';                                                           //当天最迟配送商品最早配送结束时间
        $deliverSpace = 0;                                                              //0、只有当天配送的商品 1、有隔天配送的商品

        if(isset($bill_array['goods']['general']) && !empty($bill_array['goods']['general'])){

            if(!isset($_REQUEST['goods_info']) || empty($_REQUEST['goods_info'])){
                returnJsonData('参数错误');
            }

            $goods_info = $_REQUEST['goods_info'];

            //遍历购物车商品信息 add by allen.qiang
            foreach($bill_array['goods']['general'] as &$goods){

                $new_goods = $goods;

                //当前商品总数
                $goods_amount = $goods['goods_amount'];

                //当前商品SKU编码 add by allen.qiang 2015-05-04
                $product_code = $new_goods['product_code'];

                //判断全局商品限购数量 add by allen.qiang 2015-05-18
                if($sysConfig && isset($sysConfig['goods_limit_num']) && !empty($sysConfig['goods_limit_num'])){

                    $goodsLimit = (array)json_decode($sysConfig['goods_limit_num']);
                    $goodsLimitTxt = isset($sysConfig['goods_limit_txt'])&&!empty($sysConfig['goods_limit_txt'])?(array)json_decode($sysConfig['goods_limit_txt']):array();

                    if(isset($goodsLimit[$product_code]) && $goods_amount>$goodsLimit[$product_code]){
                        $msg = isset($goodsLimitTxt[$product_code])?$goodsLimitTxt[$product_code]:'选购数量不能超过'.$goodsLimit[$product_code];
                        returnJsonData($msg);
                    }
                }

                //判断活动商品限购数量 add by allen.qiang 2015-05-15
                if($haveActivity && isset($config['goods_limit_num']) && !empty($config['goods_limit_num'])){

                    $goodsLimit = (array)json_decode($config['goods_limit_num']);
                    $goodsLimitTxt = isset($sysConfig['goods_limit_txt'])&&!empty($sysConfig['goods_limit_txt'])?(array)json_decode($sysConfig['goods_limit_txt']):array();

                    if(isset($goodsLimit[$product_code]) && $goods_amount>$goodsLimit[$product_code]){
                        $msg = isset($goodsLimitTxt[$product_code])?$goodsLimitTxt[$product_code]:'选购数量不能超过'.$goodsLimit[$product_code];
                        returnJsonData($msg);
                    }
                }

                //判断每日配送量 add by allen.qiang 2015-0-04
                if($haveActivity && isset($config['daily_limit']) && !empty($config['daily_limit'])){

                    //活动配置的每日配送量数组对象
                    $dailyLimit = json_decode($config['daily_limit']);

                    //有该商品判断库存
                    if(isset($dailyLimit->$product_code) && !empty($dailyLimit->$product_code)){

                        //配送城市ID
                        $userDeliverCityID = $bill_array['master']['cityid'];

                        //不同城市每日配送量
                        $goodsDailyNumArr = $dailyLimit->$product_code;

                        if(isset($goodsDailyNumArr->$userDeliverCityID)){

                            $goodsDailyNum = $goodsDailyNumArr->$userDeliverCityID;

                            //用户选择的配送日期
                            $userSendDate = $bill_array['master']['send_date'];

                            //查询商品当前配送日期售出数量
                            $currGoodsSaleNumSql = "SELECT SUM(goods.goods_amount) AS num FROM bill_goods AS goods,bill_master AS bill".
                                " WHERE goods.bill_no = bill.bill_no AND goods.product_code = '{$product_code}' AND bill.deliver_cityid = {$userDeliverCityID} AND bill.send_date ='{$userSendDate}' AND bill.bill_status <> 10 AND bill.createTime > '{$config['start_time']}'";

                            $currGoodsSaleNumRow = $G_SHOP->DBCA->stmt_query($currGoodsSaleNumSql);

                            //售出数量
                            $currGoodsSaleNum = $currGoodsSaleNumRow[0]->num;

                            //剩余数量
                            $GoodsSurplusNum = !is_null($currGoodsSaleNum)?intval($goodsDailyNum-$currGoodsSaleNum):intval($goodsDailyNum);

                            //判断购买数量是否合法
                            if($goods_amount>$GoodsSurplusNum){

                                $dailyLimitTips = isset($config['daily_limit_txt'])?json_decode($config['daily_limit_txt']):false;

                                $dailyLimitTip = isset($dailyLimitTips->$product_code)?$dailyLimitTips->$product_code:'您好，'.$userSendDate.'当天的“'.$new_goods['goods_name'].'”配送量已满，请选择其他配送时间，谢谢！';

                                returnJsonData($dailyLimitTip);

                            }
                        }
                    }
                }

                //判断商品库存剩余量 add by allen.qiang 2015-0-04
                if($haveActivity && isset($config['total_limit']) && !empty($config['total_limit'])){

                    //活动配置的配送总量数组对象
                    $totalLimit = json_decode($config['total_limit']);

                    //有该商品判断库存
                    if(isset($totalLimit->$product_code) && !empty($totalLimit->$product_code)){

                        //活动商品总库存数
                        $goodsTotalNum = $totalLimit->$product_code;

                        //查询本次活动上线期间该商品当前期售出数量
                        $currGoodsSaleNumSql = "SELECT SUM(goods.goods_amount) AS num FROM bill_goods AS goods,bill_master AS bill".
                            " WHERE goods.bill_no = bill.bill_no AND goods.product_code = '{$product_code}' AND bill.bill_status <> 10 AND bill.createTime > '{$config['start_time']}'";

                        $currGoodsSaleNumRow = $G_SHOP->DBCA->stmt_query($currGoodsSaleNumSql);

                        //售出数量
                        $currGoodsSaleNum = $currGoodsSaleNumRow[0]->num;

                        //剩余数量
                        $GoodsSurplusNum = !is_null($currGoodsSaleNum)?intval($goodsTotalNum-$currGoodsSaleNum):intval($goodsTotalNum);

                        //判断购买数量是否合法
                        if($goods_amount>$GoodsSurplusNum){

                            $totalLimitTips = isset($config['total_limit_txt'])?json_decode($config['total_limit_txt']):false;

                            $totalLimitTip = isset($totalLimitTips->$product_code)?$totalLimitTips->$product_code:'非常抱歉，“'.$new_goods['goods_name'].'”已售罄，请挑选其它心仪商品！';

                            returnJsonData($totalLimitTip);
                        }
                    }
                }

                $goods_info_goods = isset($goods_info[$goods['postID']]) ? array_values($goods_info[$goods['postID']]) : null;

                //多个数量的商品打散成单个商品，不知道是不是和生产有关系或者和配送也有关系 add by allen.qiang
                for($i=0;$i<$goods_amount;$i++){

                    $goods_fittings = $goods['fittings'];

                    $new_goods['birthday_card'] = isset($goods_info_goods[$i]['birthday_card'])?$goods_info_goods[$i]['birthday_card']:'';
                    $new_goods['productRemark'] = isset($goods_info_goods[$i]['goods_remark'])?$goods_info_goods[$i]['goods_remark']:'';

                    //如果有活动在线，并且设置了商品的生产备注，添加生产备注 add by allen.qiang
                    if($haveActivity && isset($config['goods_remark']) && !empty($config['goods_remark'])){

                        //活动配置生产备注
                        $goodsRemark = json_decode($config['goods_remark']);

                        //添加生产备注
                        if(isset($goodsRemark->$product_code) && !empty($goodsRemark->$product_code)){
                            $new_goods['productRemark'] = $goodsRemark->$product_code;
                        }

                    }

                    $new_goods['segmentation'] = isset($goods_info_goods[$i]['segmentation'])?$goods_info_goods[$i]['segmentation']:'';

                    //默认生日牌
                    if(isset($goods_info_goods[$i]['bs_card']) && $goods_info_goods[$i]['bs_card'] == 1 && $new_goods['birthday_card'] == ''){
                        $new_goods['birthday_card'] = 'happy birthday';
                    }

                    //商品配件
                    if(is_array($goods_fittings)){

                        foreach($goods_fittings as &$f){

                            //购买配件
                            if(isset($goods['buyFittings'][$i])){
                                foreach($goods['buyFittings'][$i] as &$fittings){
                                    if($fittings['fitID'] == $f['fitID']){
                                        $f['buyNum'] += $fittings['buyNum'];
                                        $f['buyMoney'] += $fittings['buyMoney'];
                                    }
                                }
                            }

                            //生日蜡烛
                            if($f['fitID'] == 53){
                                if(isset($goods_info_goods[$i]['bs_candle']) && $goods_info_goods[$i]['bs_candle'] == 1){
                                    $f['quantity'] = 1;
                                }else{
                                    $f['quantity'] = 0;
                                    unset($f);
                                }
                            }

                        }
                    }

                    //覆盖获取额外购买配件
                    $new_goods['fittings'] = $goods_fittings;

                    unset($new_goods['buyFittings']);

                    $new_goods['goods_amount'] = 1;

                    $bill_goods[] = $new_goods;
                }

                if(isset($goods['is_buy']) && $goods['is_buy'] == 0)
                    continue;

                //查询商品信息
                $args_array = array(
                    'postID' => $goods['postID']
                );

                $goods_array = $quanliGoods->searchGoodsSaleDetail( $args_array );

                //配送间隔
                if ($goods_array['deliverSpace'] > $max_interval)
                    $max_interval = $goods_array['deliverSpace'];

                //当天下单/配送时间控制
                if ($max_interval == 0) {

                    $arg_array = array(
                        'postID' => $goods_array['postID'],
                        'nowTime' => date('H:i:s')
                    );

                    //查询商品配送时间
                    $deliver_relation_array = $goodsDeliver->searchGoodsDeliverRelation( $arg_array );

                    if ($deliver_relation_array) {

                        $deliver_relation_array  = $deliver_relation_array[0];

                        if ($start_time == '') {

                            //第一个商品直接读取开始和结束时间
                            $start_time = $deliver_relation_array['startDeliverTime'];
                            $end_time = $deliver_relation_array['endDeliverTime'];

                        } else {

                            //从第二个商品开始判断开始和结束时间
                            if ($deliver_relation_array['startDeliverTime'] > $start_time) {
                                $start_time = $deliver_relation_array['startDeliverTime'];
                            }

                            if ($deliver_relation_array['endDeliverTime'] < $end_time) {
                                $end_time = $deliver_relation_array['endDeliverTime'];
                            }
                        }
                    } else {
                        $max_interval++;
                    }
                }

                //查询间隔为0的商品最迟配送时间
                if ($goods_array['deliverSpace'] == 0) {

                    $deliver_relation_obj =& $G_SHOP->DBCA->stmt_query('SELECT * FROM goods_deliver_relation WHERE postID = ? ORDER BY startDeliverTime ASC LIMIT 1', 'i', $goods_array['postID']);

                    if ($startDeliverTime == '') {

                        $startDeliverTime = $deliver_relation_obj[0]->startDeliverTime;
                        $endDeliverTime = $deliver_relation_obj[0]->endDeliverTime;

                    } else {

                        if ($deliver_relation_obj[0]->startDeliverTime > $startDeliverTime) {
                            $startDeliverTime = $deliver_relation_obj[0]->startDeliverTime;
                        }

                        if ($deliver_relation_obj[0]->endDeliverTime < $endDeliverTime) {
                            $endDeliverTime = $deliver_relation_obj[0]->endDeliverTime;
                        }
                    }

                } else {
                    $deliverSpace = 1;
                }

                if ($startDeliver == '') {

                    $startDeliver = $goods_array['startDeliver'];
                    $endDeliver = $goods_array['endDeliver'];

                } else {

                    if ($goods_array['startDeliver'] > $startDeliver) {
                        $startDeliver = $goods_array['startDeliver'];
                    }

                    if ($goods_array['endDeliver'] < $endDeliver) {
                        $endDeliver = $goods_array['endDeliver'];
                    }

                }

                if ($goods_array['cutTime'] != '00:00:00') {
                    if ($cutTime == '' || $cutTime > $goods_array['cutTime']) {
                        $cutTime = $goods_array['cutTime'];
                    }
                }
            }
        }

        if ($deliverSpace == 0 && empty($cutTime)) {
            $cutTime = '23:59:59';
        }

        if ($max_interval > 0) {
            if ($deliverSpace == 0 && $cutTime < date('H:i:s')) {
                $start_time = $startDeliverTime;
                $end_time = $endDeliverTime;
            } else {
                $start_time = $startDeliver;
                $end_time = $endDeliver;
            }
            if ($deliverSpace == 1 && $cutTime < date('H:i:s')) {
                $max_interval += 1;
            }
        }

        //判断配送时间和配送日期是否合法 add by allen.qiang 2015-05-20 Start

        //如果活动定义了配送开始时间
        if($haveActivity && isset($config['send_start_date']) && !empty($config['send_start_date'])){

            $max_interval = $send_date_interval;

            $send_start_date = $config['send_start_date']>date(G_DEFAULT_DATE_FORMAT)?$config['send_start_date']:date(G_DEFAULT_DATE_FORMAT);

            $send_date = date(G_DEFAULT_DATE_FORMAT,strtotime("+$max_interval day",strtotime($send_start_date)));

        }else{

            $send_date = date(G_DEFAULT_DATE_FORMAT,strtotime("+$max_interval day"));
        }

        //如果活动设置了自定义配送时间段 重置配送开始时间和结束时间
        if($haveActivity && isset($config['custom_send_time']) && !empty($config['custom_send_time'])){

            $custom_send_time = (array)json_decode($config['custom_send_time']);

            $start_time = $startDeliver = $custom_send_time['send_start_time'];

            $end_time = $endDeliver = $custom_send_time['send_end_time'];
        }

        if ($bill_array['master']['send_date'] < $send_date) {

            returnJsonData('最早配送日期为：' . $send_date . '，请重新选择配送日期');
        } else if ($bill_array['master']['send_date'] == $send_date) {

            if ($bill_array['master']['send_start_time'] < $start_time || $bill_array['master']['send_start_time'] > $end_time) {
                returnJsonData('配送开始时间必须在' . $start_time . ' ~ ' . $end_time . '内.');
            }
        } else {

            if ($bill_array['master']['send_start_time'] < $startDeliver || $bill_array['master']['send_start_time'] > $endDeliver) {
               returnJsonData('配送开始时间必须在' . $startDeliver . ' ~ ' . $endDeliver . '内。');
            }
        }

        //判断配送时间和配送日期是否合法 add by allen.qiang 2015-05-20 End

        $bill_array['goods']['general'] = $bill_goods;
        /*
         * ===============================
         * ===========商品信息End============
         * ===============================
         */


        /*===========发票内容Start============*/
        $errMesssage = '';
        if (!$this->setShopBillInvoice($bill_array,$errMesssage)){
            returnJsonData($errMesssage);
        }
        /*===========发票内容End============*/


        /*===========订单留言Start============*/
        if (!isset($_REQUEST['remark']) || empty($_REQUEST['remark'])) {
            $bill_array['master']['remark'] = null;
        } else {
            $bill_array['master']['remark'] = $_REQUEST['remark'];
        }
        //添加配送备注
        if($haveActivity && isset($config['remark']) && !empty($config['remark'])){
            $bill_array['master']['remark'] = $config['remark'];
        }
        /*订单留言End==========================*/


        /*===========付款方式==================*/
        if(isset($bill_array['master']['pay_type']) && $bill_array['master']['pay_type'] == 1){
            if(!isset($bill_array['master']['payment_method_id']) || !is_numeric($bill_array['master']['payment_method_id'])){
                returnJsonData('请选择付现方式');
            }
        }else{
            $bill_array['master']['payment_method_id'] = null;
            $bill_array['master']['payment_method_name'] = null;
            $bill_array['master']['payment_method_type'] = null;
        }
        /* ===========付款方式end===================*/


        /*===========异地付款start==================*/
        if(isset($_REQUEST['is_pay_other'] ) && $_REQUEST['is_pay_other'] == 1){

            if(!isset($bill_array['master']['payment_method_id']) || empty($bill_array['master']['payment_method_id'])){
                returnJsonData('请选择货到付款方式');
            }

            $other_address_pay = $_REQUEST['other_address_pay'];

            if(!is_array($other_address_pay)){
                returnJsonData('参数错误');
            }

            if(!isset($other_address_pay['address']) || empty($other_address_pay['address'])){
                returnJsonData('异地付款地址必须填写');
            }

            if(!isset($other_address_pay['date']) || empty($other_address_pay['date'])){
                returnJsonData('异地付款日期必须填写');
            }

            if(!isset($other_address_pay['time']) || empty($other_address_pay['time'])){
                returnJsonData('异地付款时间必须填写');
            }

            if(!isset($other_address_pay['custName']) || empty($other_address_pay['custName'])){
                returnJsonData('异地付款人必须填写');
            }
            if(!isset($other_address_pay['mobile']) || empty($other_address_pay['mobile'])){
                returnJsonData('异地付款人手机必须填写');
            }

            $time_array = explode('~',$other_address_pay['time']);
            $bill_array['other_address_pay'] = array(
                'address' => $other_address_pay['address'],
                'date' => date(G_DEFAULT_DATE_FORMAT,strtotime($other_address_pay['date'])),
                'startTime' => date('H:i:s',strtotime($time_array[0])),
                'endTime' => date('H:i:s',strtotime($time_array[1])),
                'custName' => $other_address_pay['custName'],
                'mobile' => $other_address_pay['mobile']
            );

            $bill_array['master']['bill_other_address_pay'] = 1;
        }


        /**
         * 特殊状态
         * 1：无密码登录
         * 2：超出配送站运能上线
         * 3：异地付款
         * 4：大客户
         */
        if($G_SHOP->isGuest == 1){
            $bill_array['master']['special_status'] = 1;
        }else{
            if($_REQUEST['pay_type_radio'] == 3){
                $bill_array['master']['special_status'] = 3;
            }elseif(isset($bill_array['master']['explode_bill_sign']) && $bill_array['master']['explode_bill_sign'] == 1){
                $bill_array['master']['special_status'] = 2;
            }
        }
        /*===========异地付款end============*/

        //实例订单类
        $billEdit = new billEdit( $G_SHOP->DBCA );
        $bill_array['pcustID'] = $G_SHOP->currentPCustID;

        $bill_array['master']['billPlatform'] = 1;                                                  //订单平台
        $bill_array['master']['billType'] = 1;                                                      //订单类型

        if (!isset($bill_array['master']['billPromotion']) || empty($bill_array['master']['billPromotion'])) {
            $bill_array['master']['billPromotion'] = 1;                                             //促销渠道
        }

        $bill_array['master']['urgent'] = '';                                                       //订单标识

        /*******设置订单来源信息********/
        $this->setShopBillChannel($bill_array);

        /*******生成订单数据************/
        $result_array = $billEdit->creareBillData( $bill_array, $G_SHOP->currentCustomerID );
        //判断返回数据
        if ($result_array['code'] == 200) {

            /*******生成redis中订单数据key*********/
            $bill_index = $bill_array['bill_no'] . $G_SHOP->currentPCustID;

            /*******保存订单信息到redis************/
            $G_SHOP->sessionCache_set('bill_' . $bill_index, $bill_array, 0, true);

            //http请求执行时间过长会导致本地下单失败，测试时把使用内部函数saveBillData就可以了。Add by allen.qiang Start
            if(G_LAN_DAMAIN == 'http://127.0.0.1:8000'){
                $request_result_array = $billEdit->saveBillData($bill_index);
            }else{
                $request_result_array = $quanliHttp->get( G_LAN_DAMAIN . '/app_thread_async/billEdit.php?bill_index=' . $bill_index );
            }
            //http请求执行时间过长会导致本地下单失败，测试时把使用内部函数saveBillData就可以了。Add by allen.qiang End

            if($request_result_array['code'] == 200){

                $bill_array = $G_SHOP->sessionCache_get('bill_' . $bill_index, true);

                if($bill_array['bill_status'] == 2){
                    $result_array = array('code' => 404,'message' => $bill_array['message']);
                }elseif($bill_array['bill_status'] == 0){
                    $result_array = array( 'code' => 404, 'message' => '订单提交失败');
                }else{
                    $result_array = array('code' => 200,'bill_no' => $bill_array['bill_no'],'bill_code' => $bill_array['bill_code']);

                    //add by 20141105 allen.qiang FUN-AC-0013-销售BD双11活动 start
                    $cddArray = $result_array;
                    $this->activities($cddArray);
                    $this->use_Integral($cddArray);
                    //add by 20141121 allen.qiangFUN-AC-0018-会员部感恩节活动 end
                }

                try
                {
                    $key1 = $G_SHOP->get_cookie_info('__etrack_key1');
                    $key2 = $G_SHOP->get_cookie_info('__etrack_key2');
                    $key3 = $G_SHOP->get_cookie_info('__etrack_key3');

                    if( $key2 == 'valentine' )
                    {

                        $valentine_extend = new entity('activities_extend');
                        $valentine_extend->activityNumber = 'valentine';
                        $valentine_extend->classifyID = $bill_array['bill_no'];
                        $valentine_extend->extend_1 = $bill_array['bill_code'];
                        $valentine_extend->extend_4 = $key1;
                        $valentine_extend->extend_5 = $key2;
                        $valentine_extend->extend_6 = $key3;
                        $valentine_extend->extend_7 = $this->fromCharCode( explode(',',$key3));

                        $fragment_arr = parse_url($valentine_extend->extend_7);

                        $param_array = $this->convertUrlQuery( $fragment_arr['fragment'] );

                        $valentine_extend->extend_8 = $param_array['da'];
                        $valentine_extend->extend_9 = $param_array['bd'];;
                        $valentine_extend->extend_10 = $param_array['msg'];
                        $G_SHOP->DBCA->save($valentine_extend);
                    }
                }catch (Exception $e)
                {
                    error_log($e->getMessage());
                }

                //删除订单缓存数据
                $G_SHOP->sessionCache_remove('bill_' . $bill_index, true);

                //*********************************************************************************
                // CPS推送代码块 本区块代码暂不启用。根据具体客户需定制，需与第三方合作商对接 start

                //                // CPS推送代码块 本区块代码暂不启用。根据具体客户需定制，需与第三方合作商对接 start
                //                $cps_info = $G_SHOP->get_cookie_info('CPS_INFO');
                                //判断是否CPS渠道订单，是否开启cps/dsp
                //                if ($cps_info && G_AD_ALLIANCE) {
                //
                //                    $cps_info_array = explode(':', $cps_info);
                //
                //                    $http_array = array(
                //                        'bill_no' => $bill_array['bill_no'],
                //                        'cps_info' => $cps_info
                //                    );
                //
                //                    //判断推送文件是否存在，若存在调用推送数据 add by allen.qiang 2015-05-27 Start
                //
                //                    $file_path = G_APPLICATION_BASEPATH.'cps/'.$cps_info_array[0].'/push.php';
                //
                //                    $cps_path = '/cps/'.$cps_info_array[0].'/push.php';
                //
                //                    if(file_exists($file_path))
                //                    {
                //                        $quanliHttp->post(G_LAN_DAMAIN . $cps_path, $http_array);
                //                    }
                //                }
                //                // CPS推送代码块 本区块代码暂不启用。根据具体客户需定制，需与第三方合作商对接 end

                // CPS推送代码块 本区块代码暂不启用。根据具体客户需定制，需与第三方合作商对接 end
                //*********************************************************************************
            }
        }
        //判断返回数据
        echo json_encode($result_array);
    }

    /****************************
     * 整理商城订单中渠道信息****
     ***************************/
    function setShopBillChannel(&$bill_array){
        $billChannel = 1;
        if(isset($_REQUEST['source']) && !empty($_REQUEST['source'])){

            switch($_REQUEST['source']){

                case 'web':
                    $billChannel = 1;
                    break;

                case 'wap':
                    $billChannel = 2;
                    break;

                case 'weixin':
                    $billChannel = 3;
                    break;
            }
        }

        $bill_array['master']['billChannel'] = $billChannel;//订单渠道
    }

    /****************************
     * 整理商城订单中的发票信息**
     ***************************/
    function setShopBillInvoice(&$bill_array , &$errMessage){
        global $G_SHOP;
        if (isset($_REQUEST['invoice']) && $_REQUEST['invoice'] == 1) {

            if(!isset($_REQUEST['invoice_title_type']) || !is_numeric($_REQUEST['invoice_title_type'])){
                $errMessage = '发票抬头类型必须选择';
                return false;
            }

            if($_REQUEST['invoice_title_type'] != 1 && empty($_REQUEST['invoice_title'])){
                $errMessage = '发票抬头必须填写';
                return false;
            }

            if(!in_array($_REQUEST['invoice_title_type'],array(1,2))){
                $errMessage = '发票抬头类型不正确';
                return false;
            }

            if($_REQUEST['invoice_title_type'] == 1 && empty($_REQUEST['invoice_title_type'])){
                $_REQUEST['invoice_title'] = '';
            }

            if($_REQUEST['invoice_title_type'] != 1 && empty($_REQUEST['invoice_title'])){
                $errMessage = '发票抬头必须填写';
                return false;
            }

            if(isset($_REQUEST['invoice_content_id']) && empty($_REQUEST['invoice_content_id'])){
                $errMessage = '发票内容必须选择';
                return false;
            }

            //包含发票类
            quanli_require('module/base/customer/custInvoice.class.php');
            $custInvoice = new custInvoice();

            $arg_array = array(
                'pcustID' => $G_SHOP->currentPCustID,
                'invoice_title' => $_REQUEST['invoice_title'],
                'invoice_title_type' => $_REQUEST['invoice_title_type']
            );
            $searchCustInvoice = $custInvoice->searchCustInvoice($arg_array);

            if($searchCustInvoice){
                $_REQUEST['invoiceID'] = $searchCustInvoice[0]['invoiceID'];
            }else{
                $_REQUEST['invoiceID'] = 0;
            }

            $_REQUEST['creator'] = $G_SHOP->currentCustomerID;
            $_REQUEST['pcustID'] = $G_SHOP->currentPCustID;
            $_REQUEST['invoice_type'] = 1;

            $result_array = $custInvoice->editCustInvoice( $_REQUEST );

            if($result_array['code'] != 200){
                returnJsonData($result_array['message']);
            }else{
                $bill_array['master']['invoice'] = 1;
                $bill_array['master']['invoiceID'] = $result_array['data']['invoiceID'];
                $bill_array['master']['invoice_type'] = $result_array['data']['invoice_type'];
                $bill_array['master']['invoice_title_type'] = $result_array['data']['invoice_title_type'];
                $bill_array['master']['invoice_title'] = $result_array['data']['invoice_title'];
                $bill_array['master']['invoice_content_id'] = $_REQUEST['invoice_content_id'];
                $bill_array['master']['invoice_content'] = $_REQUEST['invoice_content'];
            }

        }else{
            $bill_array['master']['invoice'] = 0;
            $bill_array['master']['invoiceID'] = 0;
            $bill_array['master']['invoice_type'] = null;
            $bill_array['master']['invoice_title_type'] = null;
            $bill_array['master']['invoice_title'] = null;
            $bill_array['master']['invoice_content_id'] = null;
            $bill_array['master']['invoice_content'] = null;
        }
        return true;
    }


    //add by sunqiang
    function fromCharCode($codes) {
        if (is_scalar($codes)) $codes= func_get_args();
        $str= '';
        foreach ($codes as $code) $str.= $this->u2utf8($code);
        return $str;
    }

    function u2utf8($c) {
        $str="";
        if ($c < 0x80) $str.= chr( $c );
        else if ($c < 0x800) {
            $str.=chr(0xC0 | $c>>6);
            $str.=chr(0x80 | $c & 0x3F);
        } else if ($c < 0x10000) {
            $str.=chr(0xE0 | $c>>12);
            $str.=chr(0x80 | $c>>6 & 0x3F);
            $str.=chr(0x80 | $c & 0x3F);
        } else if ($c < 0x200000) {
            $str.=chr(0xF0 | $c>>18);
            $str.=chr(0x80 | $c>>12 & 0x3F);
            $str.=chr(0x80 | $c>>6 & 0x3F);
            $str.=chr(0x80 | $c & 0x3F);
        }
        return $str;
    }

    function convertUrlQuery($query)
    {
        $queryParts = explode('&', $query);

        $params = array();
        foreach ($queryParts as $param)
        {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }

        return $params;
    }

    //add by sunqiang

    /**
     * 获得订单列表信息
     */
    private function getBillList() {

        global $G_SHOP;

        quanli_include('module/base/bill/billSearch.class.php');
        quanli_include('module/base/goods/quanliGoods.class.php');
        quanli_include('module/base/bill/billComplain.class.php');

        //检查是否登录
        if (!$G_SHOP->currentPCustID) {
            returnJsonData('请先登录', 404);
        }

        if (!isset($_REQUEST['page']) || !quanli_is_int($_REQUEST['page'])) {
            $_REQUEST['page'] = 1;
        }

        //实例订单类
        $billSearch = new billSearch();

        //实例商品类
        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        $result_array = array();

        //查询订单信息
        $args_array = array(
            'pcustID' => $G_SHOP->currentPCustID,
            'page' => $_REQUEST['page'],
            'rp' => 5,
            'sortname' => 'bill_no',
            'sortorder' => 'DESC'
        );
        if (isset($_REQUEST['stat']) && quanli_is_int($_REQUEST['stat'])) {
            switch($_REQUEST['stat']) {

                case 2:
                    $args_array['bill_status'] = 7;
                    break;

                case 3:
                    $args_array['extend'] = ' AND bill_status = 0 AND pay_type = 2 AND pay_status <> 1';
                    break;

                case 4:
                    $args_array['bill_status'] = 5;
                    break;

                case 5:
                    $args_array['extend'] = ' AND bill_status = 7 AND is_comment = 0';
                    break;

                default:
                    break;

            }
        }
        if (isset($_REQUEST['search']) && !empty($_REQUEST['search'])) {
            if (is_numeric($_REQUEST['search'])) {
                $args_array['bill_code'] = $_REQUEST['search'];
            } else {
                $args_array['goods_name_str'] = $_REQUEST['search'];
            }
        }

       //add by allen.qiang  2015年1月8日 FUN-AC-0028 start
        if (isset($_REQUEST['billPlatform']) && !empty($_REQUEST['billPlatform'])) {
            $args_array['billPlatform'] = $_REQUEST['billPlatform'];
        }
       //add by allen.qiang  2015年1月8日 FUN-AC-0028 end
        $bill_array = $billSearch->searchBillInfo( $args_array );
        if (!$bill_array) {
            returnJsonData('订单信息没有找到', 404);
        }

        foreach($bill_array as &$bill) {

            $goods_args_array = array(
                'bill_no' => $bill['bill_no']
            );
            $bill_goods_array = $billSearch->searchBillGoods( $goods_args_array );

            $billComplain = new billComplain();
            //查询投诉信息
            $billComplain_array = $billComplain->billComplainSearch( $goods_args_array );

            //查询订单商品信息
            if (isset($_REQUEST['op'])) {

                foreach($bill_goods_array as &$bill_goods) {

                    $postID = $bill_goods['goods_postID'];

                    if (isset($bill['goods'][$postID])) {
                        $bill['goods'][$postID]['goods_amount'] += 1;
                    } else {


                        //查询商品详情
                        $goods_args_array = array(
                            'postID' => $postID
                        );
                        $goods_array = $quanliGoods->searchGoodsSaleDetail( $goods_args_array );


                        $bill['goods'][$postID] = array(
                            'goods_name' => $goods_array['goodsName'],
                            'french_name' => $goods_array['frenchName'],
                            'goods_spec' => $goods_array['spec'],
                            'img_link' => $goods_array['img_link'],
                            'link' => $goods_array['link'],
                            'wap_link' => $goods_array['wap_link'],
                            'goods_amount' => 1,
                            'price' => $bill_goods['goods_purchasePrice'],
                            'segmentation' => $bill_goods['segmentation'],
                            'birthday_card' => $bill_goods['birthday_card'],
                            'goods_remark' => $bill_goods['goods_remark'],
                        );

                    }

                    //查询商品赠品
                    $fittings_args_array = array(
                        'bill_goods_no' => $bill_goods['bill_goods_no']
                    );
                    $bill_goods_fittings_array = $billSearch->searchGoodsFittingsBill( $fittings_args_array );

                    if ($bill_goods_fittings_array) {

                        foreach($bill_goods_fittings_array as &$goods_fittings) {

                            $fitID = $goods_fittings['fitID'];

                            if ($goods_fittings['buyNum'] > 0) { //额外购买

                                if (isset($bill['goods'][$postID]['extra_fittings'][$fitID])) {
                                    $bill['goods'][$postID]['extra_fittings'][$fitID]['buyNum'] += $goods_fittings['buyNum'];
                                } else {
                                    $bill['goods'][$postID]['extra_fittings'][$fitID] = array(
                                        'fitName' => $goods_fittings['fitName'],
                                        'buyNum' => $goods_fittings['buyNum'],
                                        'buyMoney' => $goods_fittings['buyMoney'],
                                        'fitUnit' => $GLOBALS['fit_unit'][$goods_fittings['fitUnit']],
                                    );
                                }

                            } else { // 赠送

                                if (isset($bill['goods'][$postID]['fittings'][$fitID])) {
                                    $bill['goods'][$postID]['fittings'][$fitID]['quantity'] += $goods_fittings['quantity'];
                                } else {
                                    $bill['goods'][$postID]['fittings'][$fitID] = array(
                                        'fitName' => $goods_fittings['fitName'],
                                        'quantity' => $goods_fittings['quantity'],
                                        'fitUnit' => $GLOBALS['fit_unit'][$goods_fittings['fitUnit']],
                                    );
                                }

                            }

                        }

                    }

                }

            } else {
                $bill['goods'] = '';
            }

//            查询投诉信息
            if( $billComplain_array ){
                $is_complain = 1;//已投诉
            }else{
                $is_complain = 0;//未投诉
            }
            $result_array['bill'][] = array(
                'createTime' => $bill['createTime'],
                'bill_no' => (string)$bill['bill_no'],
                'bill_code' => $bill['bill_code'],
                'bill_money' => $bill['bill_money'],
                'bill_receivable_money' => round($bill['bill_money'] - $bill['bill_coupon_money'] - $bill['bill_card_money'] - $bill['bill_balance_money'] - $bill['bill_points_money'] - $bill['bill_subtract_money'], 2),
                'deliver_feePaid' => $bill['deliver_feePaid'],
                'bill_status' => $bill['bill_status'],
                'shop_bill_status_name' => $bill['shop_bill_status_name'],
                'is_comment' => $bill['is_comment'],
                'pay_type' => $bill['pay_type'],
                'pay_status' => $bill['pay_status'],
                'is_complain' => $is_complain,
                'goods' => $bill['goods']
            );

        }


        $result_array['paging'] = '';
        if ($bill_array) {
            $result_array['paging'] = shop_page($args_array['page'], $args_array['count'], $args_array['rp'], 'javascript: G.bill.search(%d);', $G_SHOP->smarty);
        }

        returnJsonData('ok', 200, $result_array);

    }

    /**
     * 获得订单商品
     */
    private function getBillGoods() {

        global $G_SHOP;

        quanli_include('module/base/bill/billSearch.class.php');
        quanli_include('module/base/goods/quanliGoods.class.php');

        //检查是否登录
        if (!$G_SHOP->currentPCustID) {
            returnJsonData('请先登录', 404);
        }

        if (!isset($_REQUEST['bill_no']) || empty($_REQUEST['bill_no'])) {
            returnJsonData('缺少参数', 404);
        }

        //实例订单类
        $billSearch = new billSearch();

        //实例商品类
        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        //查询订单信息
        $args_array = array(
            'pcustID' => $G_SHOP->currentPCustID,
            'bill_no' => $_REQUEST['bill_no']
        );
        $bill_array = $billSearch->searchBillInfo( $args_array );
        if (!$bill_array) {
            returnJsonData('订单信息没有找到', 404);
        }
        if ($bill_array[0]['is_comment'] == 1) {
            returnJsonData('订单商品已评价', 404);
        }

        //查询订单商品信息
        $bill_goods_array = $billSearch->searchBillGoods( $args_array );

        $data_array = array();

        foreach($bill_goods_array as &$bill_goods) {

            $postID = $bill_goods['goods_postID'];

            if (isset($bill['goods'][$postID])) {
                $data_array[$postID]['goods_amount'] += 1;
            } else {

                //查询商品详情
                $goods_args_array = array(
                    'postID' => $postID
                );
                $goods_array = $quanliGoods->searchGoodsSaleDetail( $goods_args_array );

                $data_array[$postID] = array(
                    'postID' => $goods_array['postID'],
                    'goods_name' => $goods_array['goodsName'],
                    'french_name' => $goods_array['frenchName'],
                    'goods_spec' => $goods_array['spec'],
                    'img_link' => $goods_array['img_link'],
                    'link' => $goods_array['link'],
                    'wap_link' => $goods_array['wap_link'],
                    'goods_amount' => 1,
                );

            }

        }

        returnJsonData('ok', 200, $data_array);

    }

    /**
     * 检查在线支付状态
     */
    private function checkOnlinePay() {

        global $G_SHOP;

        if (!isset($_REQUEST['bill_no']) || empty($_REQUEST['bill_no'])) {
            returnJsonData('参数错误');
        }

        quanli_include('module/base/bill/billSearch.class.php');

        //实例化订单类
        $billSearch = new billSearch();


        /**
         * ====================
         * 查询订单信息
         * ====================
         */
        $arg_array = array(
            'pcustID' => $G_SHOP->currentPCustID,
            'bill_no' => $_REQUEST['bill_no']
        );
        $bill_array = $billSearch->searchBillInfo($arg_array);
        if ($bill_array[0]['pay_status'] == 1) {
            returnJsonData('ok', 200, 1);
        } else {
            returnJsonData('ok', 200, 0);
        }

    }
    /*
 *  BD双11活动送礼包
 *  @package ajax
 *  @backend  shop
 *  @author   allen.qiang <allen.qiang@fistforward.com>
 *  20141105 add by allen.qiang FUN-AC-0013-销售BD双11活动
 *  $reust 订单提交数组
 */
    private function  activities($reust){

        global $G_PGLOB;
        //载入活动类
        quanli_require('module/base/activity/activitySpike.class.php');
        //实例化活动类
        $activityspike=new activitySpike();

        $promotion_sql="SELECT bill_no,bill_goods_no,promotionID FROM  bill_promotion_log where bill_no=? and promotionID =?";
        $promotion_query=$G_PGLOB->DBCA->stmt_query($promotion_sql,'ss',$reust['data']['bill_no'],$activityspike->selector_goods);
        //查询会员ID 订单编号 pay_type==1 货到付款  pay_type==2 在线支付
        $bill_master_sql="SELECT pcustID,bill_code FROM  bill_master where bill_no=?";
        $bill_master_query=$G_PGLOB->DBCA->stmt_query($bill_master_sql,'s',$reust['data']['bill_no']);
        //货到付款 或 在线支付金额不为空
        if(!is_null($promotion_query)){//先判断下是不是NULL再循环 Add By allen.qiang 2015-05-01
            foreach ($promotion_query as $promotion_obj){
                //插入活动拓展表数据
                $activities_extend=new entity("activities_extend");
                $activities_extend->activityNumber=11000;                                           //活动编号
                $activities_extend->classifyID=11002;                                               //分类ID
                $activities_extend->extend_1=$bill_master_query[0]->bill_code;                     //订单编号
                $activities_extend->extend_7=$promotion_obj->promotionID;                       //促销渠道ID
                $activities_extend->extend_8=$bill_master_query[0]->pcustID;                       //会员ID
                $activities_extend->extend_9=$promotion_obj->bill_goods_no;                       //订单商品流水号
                $G_PGLOB->DBCA->save($activities_extend);
            }
        }
    }
    /*
     *  使用感恩节优惠券送积分
     *  @package ajax
     *  @backend  shop
     *  @author   allen.qiang <allen.qiang@fistforward.com>
     *  20141121 add by allen.qiangFUN-AC-0018-销售BD双11活动
     *  $reust 订单提交数组
     */
    private function use_Integral($reust){
        global $G_SHOP;
        quanli_require('module/base/activity/activityConfig.class.php');//活动配置文件
        $activity_config = new activityConfig('Thanksgiving'); //活动配置
        $config_array = $activity_config->config;
        $couponID=$config_array['couponID'];
        quanli_require('module/func/eai.func.php');
        //实例crm类
        $crm_obj_cdd = eai_crm();
        $pcustID = $G_SHOP->currentPCustID;
        //查询该订单付款方式是货到付款的
        $bill_master_sql="SELECT count(1) as num FROM  bill_master where bill_no=? and  pay_type=?";
        $bill_master_query=$G_SHOP->DBCA->stmt_query($bill_master_sql,'ss',$reust['data']['bill_no'],1);
        //查询该订单使用的优惠券
        $use_coupon="SELECT count(1) as num FROM  bill_use_coupon where bill_no=? and  couponID in (".$couponID.") ";
        $use_coupon_query=$G_SHOP->DBCA->stmt_query($use_coupon,'s',$reust['data']['bill_no']);
        if($bill_master_query[0]->num && $use_coupon_query[0]->num){

        //积分日志记录
        $integral_log=new entity('integral_log');
        $integral_log->pcustID=$pcustID;
        $integral_log->logType='2';//感恩节积分日志类型
        $integral_log->logName='感恩节优惠券下单送500积分';
        $integral_log->logValue='500';
        $G_SHOP->DBCA->save($integral_log);//修改光棍节日志表
        //积分账户充值
        $arg_array = array(
            'pcustID' => $pcustID,   //会员ID
            'subjectId' => G_POINTS_ID,              //积分常量
            'amount' => 500,                            //积分数量
            'operator' => 'system',
            'remark' => '感恩节优惠券下单送500积分'
        );
            $zt=$crm_obj_cdd->recharge( $arg_array );
        }
    }

    //抓取网页内容（测试用）Add By allen.qiang
    public function curl_get_contents($url,$timeout=5)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);                   //设置访问的url地址
        //curl_setopt($ch,CURLOPT_HEADER,1);                     //是否显示头部信息
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);          //设置超时
        curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);   //用户访问代理 User-Agent
        curl_setopt($ch, CURLOPT_REFERER,_REFERER_);         //设置 referer
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);           //跟踪301
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);         //返回结果
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }
}
